package com.shsoft.colorfulcc;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.clj.fastble.BleManager;
import com.hb.dialog.myDialog.MyAlertDialog;
import com.shsoft.adapter.CompositeItemAdapter;
import com.shsoft.common.*;
import com.shsoft.component.*;
import com.shsoft.entity.CompositeItem;
import com.shsoft.fragment.CompositeAddFragment;
import com.shsoft.fragment.CompositeEditFragment;
import com.shsoft.myThread.*;
import com.shsoft.utils.*;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;
import org.litepal.LitePal;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MainActivity extends BaseActivity implements View.OnClickListener,View.OnLongClickListener,TextView.OnFocusChangeListener,TextView.OnEditorActionListener {
    private MyApplication app;
    public TextView titleMain, tips, upload, start, stop, selectAll, invertSelectAll,cancelSelectAll, wrong, right,icon_add, icon_clear,remain,init,intervalChoose;
    private Typeface fontTitle, iconfont;
    private LightView lightDiv;
    private LinearLayout optionDiv, color_choose,composite,add,clear;
    public MyAlertDialog myAlertDialog;
    private BleUtil bleUtil;
    public boolean isCompositeAddOpened = false; // 记录添加复合模式的fragment是否已经打开
    private Thread thread; // 显示虚拟灯光效果的线程
    private ColorBar colorBar; // 颜色选择条
    private NiceSpinner modeSpinner, colorSpinner, breathingModeSpinner, flowingWaterModeSpinner;
    private CompositeItemAdapter adapter;
    private byte[] data; // 记录移动端调试好的灯珠信息
    public Map<Integer, Integer> lights = new HashMap<>();  // 记录灯珠的预设颜色编号
    public Map<Integer, int[]> lights_4display = new HashMap<>();  // 记录用来展示的颜色
    public Map<Integer, int[]> colors = new HashMap<>();  // 记录预设的颜色
    public Map<Integer, Integer> choosedLights = new HashMap<>(); // 记录已选择的灯珠
    public int colorMode = Constant.COLOR_MODE_SINGLE; // 记录颜色模式，一开始进来是纯色模式
    public int lightMode = Constant.LIGHT_MODE_LONG; // 记录亮灯模式，一开始进来是常亮模式
    public int breathingMode = Constant.BREATHING_MODE_D_L_D; // 记录呼吸模式，一开始进来是 暗→明→暗
    public int flowingWaterMode = Constant.FLOWINGWATER_MODE_TAIL_FOLLOW; // 记录流水模式，一开始进来是 尾部跟进
    private int currentColorNum; // 当前已选择的预设颜色的编号
    private RecyclerView recycler_view; // 复合模式显示区
    private ScrollView longMode,horse,flowingWater,breathing; // 灯光模式参数区
    private LinearLayout long_circle_div,long_bright_div, long_interval_div, long_offtime_div,horse_bright_div,horse_count_div,horse_direction_div,horse_speed_div,horse_circle_div,flowingWater_bright_div,flowingWater_direction_div,flowingWater_speed_div,flowingWater_circle_div,breathing_time_div,breathing_circle_div,breathing_bright_div; // 参数区div
    public EditText long_bright, long_interval, long_offtime,long_circle,horse_bright,horse_count,horse_speed,horse_circle,flowingWater_bright,flowingWater_speed,flowingWater_circle,breathing_time,breathing_circle,breathing_bright; // 具体参数
    // 方向选择
    private RadioGroup horse_direction,flowingWater_direction;
    private RadioButton horse_clockwise,horse_anticlockwise,flowingWater_clockwise,flowingWater_anticlockwise;
    public int horse_direction_value = Constant.CLOCKWISE; // 跑马灯方向
    public int flowingWater_direction_value = Constant.CLOCKWISE; // 流水灯方向
    public boolean isPlaying = false; // 记录是否在预览模式中
    public int alpha = 250; // 记录当前的透明度
    // 颜色预设区
    public CardView color1, color2, color3, color4, color5, color6, color7, color8, color9, color10,color11, color12, color13, color14, color15, color16, color17, color18, color19, color0;
    public TextView color1_text,color2_text,color3_text,color4_text,color5_text,color6_text,color7_text,color8_text,color9_text,color10_text,color11_text,color12_text,color13_text,color14_text,color15_text,color16_text,color17_text,color18_text,color19_text,color0_text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 将软键盘设置为在最上层
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        //背景图和状态栏连在一起
        if(Build.VERSION.SDK_INT>=21){
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_main);
        //初始化控件
        initView();
        // 设置字体
        setFont();
        // 绑定点击事件
        setClickListener();
        // 蓝牙初始化
        bleUtil.bleInit(app);
        // 检查蓝牙状态
        if(BleManager.getInstance().isBlueEnable()){ // 蓝牙已开启
            // 查看权限，如果有权限，连接蓝牙
            checkBlePermission();
        }else {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, Constant.BLUETOOTH_REQUEST_CODE);
        }
    }

    //初始化控件
    private void initView(){
        app = (MyApplication) getApplication();
        titleMain = findViewById(R.id.titleMain);
        tips = findViewById(R.id.tips);
        upload = findViewById(R.id.upload);
        start = findViewById(R.id.start);
        init = findViewById(R.id.init);
        intervalChoose = findViewById(R.id.intervalChoose);
        stop = findViewById(R.id.stop);
        lightDiv = findViewById(R.id.lightDiv);
        optionDiv = findViewById(R.id.optionDiv);
        wrong = findViewById(R.id.wrong);
        right = findViewById(R.id.right);
        add = findViewById(R.id.add);
        clear = findViewById(R.id.clear);
        icon_add = findViewById(R.id.icon_add);
        icon_clear = findViewById(R.id.icon_clear);
        color_choose = findViewById(R.id.color_choose);
        colorBar = findViewById(R.id.colorBar);
        selectAll = findViewById(R.id.selectAll);
        invertSelectAll = findViewById(R.id.invertSelectAll);
        cancelSelectAll = findViewById(R.id.cancelSelectAll);
        // 复合模式显示区
        recycler_view = findViewById(R.id.recycler_view);
        List<CompositeItem> CompositeList = LitePal.where("colorMode=?",colorMode + "").order("id asc").find(CompositeItem.class);
        adapter = new CompositeItemAdapter(CompositeList,this);
        recycler_view.setLayoutManager(new LinearLayoutManager(this));
        recycler_view.setAdapter(adapter);
        // 亮灯模式和颜色模式选择区
        modeSpinner = findViewById(R.id.modeSpinner);
        modeSpinner.setBackgroundResource(R.drawable.spinner_border);
        colorSpinner = findViewById(R.id.colorSpinner);
        colorSpinner.setBackgroundResource(R.drawable.spinner_border);
        breathingModeSpinner = findViewById(R.id.breathingModeSpinner);
        breathingModeSpinner.setBackgroundResource(R.drawable.spinner_border);
        flowingWaterModeSpinner = findViewById(R.id.flowingWaterModeSpinner);
        flowingWaterModeSpinner.setBackgroundResource(R.drawable.spinner_border);
        bleUtil = new BleUtil(tips, MainActivity.this);
        initColors(); // 初始化颜色预设区控件
        initOptions(); // 初始化参数区控件
        // 初始化灯珠list里的内容，一共20种预设颜色，编号为0-19,20即为无颜色
        for(int i = 0; i < Constant.LIGHT_COUNT; i++){
            lights.put(i, 20);
            lights_4display.put(i, new int[]{1,1,1});
        }
        // 将SharedPreferences中的颜色取出来
        colors = SharedPreferencesUtil.getColors();
        // 处理颜色预设区的控件
        doColors();
    }

    // 设置字体
    private void setFont(){
        //获取assets文件夹里的字体文件
        fontTitle = Typeface.createFromAsset(getAssets(), "colorfulcc_title.ttf");
        iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        //给指定的TextView加载字体
        titleMain.setTypeface(fontTitle);
        upload.setTypeface(iconfont);
        init.setTypeface(iconfont);
        intervalChoose.setTypeface(iconfont);
        start.setTypeface(iconfont);
        stop.setTypeface(iconfont);
        selectAll.setTypeface(iconfont);
        invertSelectAll.setTypeface(iconfont);
        cancelSelectAll.setTypeface(iconfont);
        wrong.setTypeface(iconfont);
        right.setTypeface(iconfont);
        icon_add.setTypeface(iconfont);
        icon_clear.setTypeface(iconfont);
    }

    // 绑定点击事件
    private void setClickListener(){
        tips.setOnClickListener(this);
        upload.setOnClickListener(this);
        init.setOnClickListener(this);
        intervalChoose.setOnClickListener(this);
        add.setOnClickListener(this);
        clear.setOnClickListener(this);
        selectAll.setOnClickListener(this);
        invertSelectAll.setOnClickListener(this);
        cancelSelectAll.setOnClickListener(this);
        start.setOnClickListener(this);
        stop.setOnClickListener(this);
        bindColors(); // 颜色预设区事件绑定
        bindOptions(); // 参数区事件绑定
        // 下拉选项卡
        modeSpinner.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                // This example uses String, but your type can be any
                String item = (String) parent.getItemAtPosition(position);
//                MessageUtil.logDebug("选择了： " + item);
                switch (item){
                    case "常亮":
                        // 将所有的设置区都先不可见
                        invisibleAllOptions();
                        // 设置常亮可见
                        longMode.setVisibility(View.VISIBLE);
                        // 修改lightMode
                        lightMode = Constant.LIGHT_MODE_LONG;
                        break;
                    case "跑马":
                        // 将所有的设置区都先不可见
                        invisibleAllOptions();
                        // 设置跑马可见
                        horse.setVisibility(View.VISIBLE);
                        // 修改lightMode
                        lightMode = Constant.LIGHT_MODE_HORSE;
                        break;
                    case "流水":
                        // 将所有的设置区都先不可见
                        invisibleAllOptions();
                        // 设置流水可见
                        flowingWater.setVisibility(View.VISIBLE);
                        // 修改lightMode
                        lightMode = Constant.LIGHT_MODE_FLOWING_WATER;
                        break;
                    case "呼吸":
                        // 将所有的设置区都先不可见
                        invisibleAllOptions();
                        // 设置呼吸可见
                        breathing.setVisibility(View.VISIBLE);
                        // 修改lightMode
                        lightMode = Constant.LIGHT_MODE_BREATHING;
                        break;
                    case "复合模式":
                        // 将所有的设置区都先不可见
                        invisibleAllOptions();
                        // 设置复合模式可见
                        composite.setVisibility(View.VISIBLE);
                        // 修改lightMode
                        lightMode = Constant.LIGHT_MODE_COMPOSITE;
                        break;
                    default:
                        break;
                }
            }
        });
        colorSpinner.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                // This example uses String, but your type can be any
                String item = (String) parent.getItemAtPosition(position);
//                MessageUtil.logDebug("选择了： " + item);
                switch (item){
                    case "纯色":
                        if(colorMode != Constant.COLOR_MODE_SINGLE){ // 原本不是纯色模式
                            // 清空已选择列表
                            choosedLights = new HashMap<>();
                            // 设置某些控件的可见不可见
                            horse_circle_div.setVisibility(View.VISIBLE);
                            flowingWater_circle_div.setVisibility(View.VISIBLE);
                            breathing_circle_div.setVisibility(View.VISIBLE);
                            horse_count_div.setVisibility(View.VISIBLE);
                            long_circle_div.setVisibility(View.VISIBLE);
                            //设置颜色模式
                            colorMode = Constant.COLOR_MODE_SINGLE;
                            lightDiv.invalidate(); // 重新绘制灯板区域
                            setRemain(); // 重新设置剩余字节数
                            //刷新复合区步骤
                            updateRecycleView();
                        }
                        break;
                    case "混色":
                        if(colorMode != Constant.COLOR_MODE_MIX){ // 原本不是混色模式
                            // 清空已选择列表
                            choosedLights = new HashMap<>();
                            // 设置某些控件的可见不可见
                            horse_circle_div.setVisibility(View.GONE);
                            flowingWater_circle_div.setVisibility(View.GONE);
                            breathing_circle_div.setVisibility(View.GONE);
                            horse_count_div.setVisibility(View.GONE);
                            long_circle_div.setVisibility(View.GONE);
                            //设置颜色模式
                            colorMode = Constant.COLOR_MODE_MIX;
                            lightDiv.invalidate(); // 重新绘制灯板区域
                            setRemain(); // 重新设置剩余字节数
                            //刷新复合区步骤
                            updateRecycleView();
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        breathingModeSpinner.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                String item = (String) parent.getItemAtPosition(position);
                switch (item){
                    case "暗→明→暗":
                        breathingMode = Constant.BREATHING_MODE_D_L_D;
                        break;
                    case "明→暗→明":
                        breathingMode = Constant.BREATHING_MODE_L_D_L;
                        break;
                    case "明→暗":
                        breathingMode = Constant.BREATHING_MODE_L_D;
                        break;
                    case "暗→明":
                        breathingMode = Constant.BREATHING_MODE_D_L;
                        break;
                    default:
                        break;
                }
            }
        });
        flowingWaterModeSpinner.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                String item = (String) parent.getItemAtPosition(position);
                switch (item){
                    case "尾部跟进":
                        flowingWaterMode = Constant.FLOWINGWATER_MODE_TAIL_FOLLOW;
                        break;
                    case "头部回退":
                        flowingWaterMode = Constant.FLOWINGWATER_MODE_HEAD_BACK;
                        break;
                    case "灯满结束":
                        flowingWaterMode = Constant.FLOWINGWATER_MODE_FULL_FINISH;
                        break;
                    default:
                        break;
                }
            }
        });

    }

    /////////////////////////////////接口实现区///////////////////////////////////////////

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add:
                if(!isCompositeAddOpened){
                    CompositeAddFragment fragment = new CompositeAddFragment(this);
                    fragment.setCancelable(false);
                    fragment.show(getSupportFragmentManager(),"");
                    isCompositeAddOpened = true;
                }
                break;
            case R.id.clear:
                myAlertDialog = new MyAlertDialog(this).builder()
                        .setCancelable(false)
                        .setMsg("删除当前颜色模式下的所有复合步骤？")
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                LitePal.deleteAll(CompositeItem.class,"colorMode = ?", colorMode + "");
                                updateRecycleView();
                                setRemain();
                            }
                        }).setNegativeButton("返回", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                            }
                        });
                myAlertDialog.show();
                break;
            case R.id.start:
                // 如果是纯色模式且预设区没有颜色，直接返回
                if(colorMode == Constant.COLOR_MODE_SINGLE && colors.size() == 0){
                    MessageUtil.toastShort(this, "请先在预设区配置颜色");
                    break;
                }
                // 新建一个线程，操作虚拟灯的显示
                newThread();
                if(thread != null){
                    isPlaying = true;
                    thread.start();
                    // 将自己隐藏，将暂停键显示
                    start.setVisibility(View.GONE);
                    stop.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.stop:
                thread.interrupt();
                thread = null;
                isPlaying = false;
                // 将自己隐藏，将暂停键显示
                stop.setVisibility(View.GONE);
                start.setVisibility(View.VISIBLE);
                // 将灯珠设为之前设置的颜色
                alpha = 250;
                for(int i = 0; i < Constant.LIGHT_COUNT; i++){
                    int colorIndex = lights.get(i);
                    if(colorIndex == 20 || colorIndex >= colors.size()){ // 索引为20，说明是空颜色 || 索引超出预设颜色个数，将其变成空颜色
                        lights_4display.put(i,new int[]{1,1,1});
                    }else {
                        lights_4display.put(i,colors.get(colorIndex));
                    }
                }
                // 选中列表清空
                choosedLights = new HashMap<>();
                // 重新绘制灯珠区
                refreshLightsDiv();
                break;
            case R.id.tips:
//                MessageUtil.toastShort(app, "点击连接");
                // 先查看蓝牙是否打开,如果打开了，就检查权限，然后连接
                if(BleManager.getInstance().isBlueEnable()){
                    checkBlePermission();
                }else { // 没有打开，让打开蓝牙
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(intent, Constant.BLUETOOTH_REQUEST_CODE);
                }
                break;
            case R.id.upload:
                myAlertDialog = new MyAlertDialog(this).builder()
                        .setCancelable(false)
                        .setMsg("将当前配置发送给灯板？")
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if(colorMode == Constant.COLOR_MODE_SINGLE && colors.size() == 0){
                                    MessageUtil.toastShort(MainActivity.this, "纯色模式请先预设颜色");
                                    return;
                                }
                                if(lightMode == Constant.LIGHT_MODE_COMPOSITE){ // 复合模式
                                    // 查询出当前复合模式下有没有步骤
                                    List<CompositeItem> compositeList = LitePal.where("colorMode=?",colorMode + "").order("id asc").find(CompositeItem.class);
                                    if(compositeList == null || compositeList.size() == 0){
                                        MessageUtil.toastShort(MainActivity.this, "复合模式请先添加步骤");
                                        return;
                                    }
                                }
                                bleUtil.writeNewInfo();
                            }
                        }).setNegativeButton("返回", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                            }
                        });
                myAlertDialog.show();
                break;
            case R.id.selectAll:
                if(colorMode == Constant.COLOR_MODE_SINGLE){
                    MessageUtil.toastShort(this, "纯色模式下，全选功能无效");
                    return;
                }
                for(int i = 0; i < Constant.LIGHT_COUNT; i++){
                    choosedLights.put(i,i);
                }
                lightDiv.invalidate();
                break;
            case R.id.init:
                myAlertDialog = new MyAlertDialog(this).builder()
                        .setCancelable(false)
                        .setMsg("清空灯板配色？")
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // 清空已选择列表，初始化灯珠颜色列表
                                choosedLights = new HashMap<>();
                                for(int i = 0; i < Constant.LIGHT_COUNT; i++){
                                    lights.put(i, 20);
                                    lights_4display.put(i, new int[]{1,1,1});
                                }
                                lightDiv.invalidate();
                            }
                        }).setNegativeButton("返回", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                            }
                        });
                myAlertDialog.show();
                break;
            case R.id.intervalChoose:
                if(colorMode == Constant.COLOR_MODE_SINGLE){
                    MessageUtil.toastShort(this, "纯色模式下，间隔选择功能无效");
                    return;
                }
                for(int i = 0; i < Constant.LIGHT_COUNT; i++){
                    if(i % 2 == 0){
                        choosedLights.put(i,i);
                    }else {
                        choosedLights.remove(i);
                    }
                }
                lightDiv.invalidate();
                break;
            case R.id.cancelSelectAll:
                if(colorMode == Constant.COLOR_MODE_SINGLE){
                    MessageUtil.toastShort(this, "纯色模式下，取消选择功能无效");
                    return;
                }
                choosedLights = new HashMap<>();
                lightDiv.invalidate();
                break;
            case R.id.invertSelectAll:
                if(colorMode == Constant.COLOR_MODE_SINGLE){
                    MessageUtil.toastShort(this, "纯色模式下，反选功能无效");
                    return;
                }
                for(int i = 0; i < Constant.LIGHT_COUNT; i++){
                    if(choosedLights.get(i) == null){
                        choosedLights.put(i,i);
                    }else {
                        choosedLights.remove(i);
                    }
                }
                lightDiv.invalidate();
                break;
            case R.id.wrong:
                color_choose.setVisibility(View.GONE);
                break;
            case R.id.right:
                // 获取当前的rgb
                int[] currentRGB = colorBar.getCurrentRGB();
                // 保存进currentColorNum号的预设中
                colors.put(currentColorNum, new int[]{currentRGB[0], currentRGB[1], currentRGB[2]});
                // 隐藏颜色条
                color_choose.setVisibility(View.GONE);
                // 重新绘制颜色预设区
                doColors();
                // 将新的预设颜色存入SharedPreference
                SharedPreferencesUtil.setColors(colors);
                break;
            case R.id.color0:
                doColorClick(0);
                break;
            case R.id.color1:
                doColorClick(1);
                break;
            case R.id.color2:
                doColorClick(2);
                break;
            case R.id.color3:
                doColorClick(3);
                break;
            case R.id.color4:
                doColorClick(4);
                break;
            case R.id.color5:
                doColorClick(5);
                break;
            case R.id.color6:
                doColorClick(6);
                break;
            case R.id.color7:
                doColorClick(7);
                break;
            case R.id.color8:
                doColorClick(8);
                break;
            case R.id.color9:
                doColorClick(9);
                break;
            case R.id.color10:
                doColorClick(10);
                break;
            case R.id.color11:
                doColorClick(11);
                break;
            case R.id.color12:
                doColorClick(12);
                break;
            case R.id.color13:
                doColorClick(13);
                break;
            case R.id.color14:
                doColorClick(14);
                break;
            case R.id.color15:
                doColorClick(15);
                break;
            case R.id.color16:
                doColorClick(16);
                break;
            case R.id.color17:
                doColorClick(17);
                break;
            case R.id.color18:
                doColorClick(18);
                break;
            case R.id.color19:
                doColorClick(19);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onLongClick(View v) {
        switch (v.getId()) {
            case R.id.color0:
                removeColor(0);
                break;
            case R.id.color1:
                removeColor(1);
                break;
            case R.id.color2:
                removeColor(2);
                break;
            case R.id.color3:
                removeColor(3);
                break;
            case R.id.color4:
                removeColor(4);
                break;
            case R.id.color5:
                removeColor(5);
                break;
            case R.id.color6:
                removeColor(6);
                break;
            case R.id.color7:
                removeColor(7);
                break;
            case R.id.color8:
                removeColor(8);
                break;
            case R.id.color9:
                removeColor(9);
                break;
            case R.id.color10:
                removeColor(10);
                break;
            case R.id.color11:
                removeColor(11);
                break;
            case R.id.color12:
                removeColor(12);
                break;
            case R.id.color13:
                removeColor(13);
                break;
            case R.id.color14:
                removeColor(14);
                break;
            case R.id.color15:
                removeColor(15);
                break;
            case R.id.color16:
                removeColor(16);
                break;
            case R.id.color17:
                removeColor(17);
                break;
            case R.id.color18:
                removeColor(18);
                break;
            case R.id.color19:
                removeColor(19);
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
        if(i == EditorInfo.IME_ACTION_DONE){
            textView.clearFocus();
            return true;
        }
        return false;
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        if(!b){ // 失去焦点
            switch (view.getId()){
                case R.id.long_bright:
                case R.id.horse_bright:
                case R.id.flowingWater_bright:
                case R.id.breathing_bright:
                    doLostFocus(view, "100", 1,250);
                    break;
                case R.id.long_interval:
                    doLostFocus(view, "10", 0,250);
                    break;
                case R.id.long_offtime:
                    doLostFocus(view, "0", 0,250);
                    break;
                case R.id.horse_count:
                    doLostFocus(view, "1", 1,40);
                    break;
                case R.id.horse_circle:
                case R.id.flowingWater_circle:
                case R.id.breathing_circle:
                case R.id.long_circle:
                    doLostFocus(view, "1", 1,250);
                    break;
                case R.id.horse_speed:
                case R.id.flowingWater_speed:
                    doLostFocus(view, "10", 1,250);
                    break;
                case R.id.breathing_time:
                    doLostFocus(view, "2", 1,250);
                    break;
                default:
                    break;
            }
        }
    }

    // 根据当前的颜色模式和运行模式，生成相应的子线程还行亮灯操作
    private void newThread(){
        if(colorMode == Constant.COLOR_MODE_SINGLE){
            if(lightMode == Constant.LIGHT_MODE_LONG){
                if(long_bright.getText().toString().equals("") || long_interval.getText().toString().equals("") || long_offtime.getText().toString().equals("")
                || long_circle.getText().toString().equals("")){
                    MessageUtil.toastShort(this, "请完善参数");
                    return;
                }
                thread = new SingleLongThread(this);
            }else if(lightMode == Constant.LIGHT_MODE_HORSE){
                if(horse_bright.getText().toString().equals("") || horse_speed.getText().toString().equals("")|| horse_count.getText().toString().equals("")
                        || horse_circle.getText().toString().equals("")){
                    MessageUtil.toastShort(this, "请完善参数");
                    return;
                }
                thread = new SingleHorseThread(this);
            }else if(lightMode == Constant.LIGHT_MODE_FLOWING_WATER){
                if(flowingWater_bright.getText().toString().equals("") || flowingWater_speed.getText().toString().equals("")|| flowingWater_circle.getText().toString().equals("")){
                    MessageUtil.toastShort(this, "请完善参数");
                    return;
                }
                thread = new SingleFlowingWaterThread(this);
            }else if(lightMode == Constant.LIGHT_MODE_BREATHING){
                if(breathing_time.getText().toString().equals("") || breathing_circle.getText().toString().equals("")|| breathing_bright.getText().toString().equals("")){
                    MessageUtil.toastShort(this, "请完善参数");
                    return;
                }
                thread = new SingleBreathingThread(this);
            }else if(lightMode == Constant.LIGHT_MODE_COMPOSITE){
                thread = new SingleCompositeThread(this);
            }
        }else if(colorMode == Constant.COLOR_MODE_MIX){
            if(lightMode == Constant.LIGHT_MODE_LONG){
                if(long_bright.getText().toString().equals("") || long_interval.getText().toString().equals("") || long_offtime.getText().toString().equals("")){
                    MessageUtil.toastShort(this, "请完善参数");
                    return;
                }
                thread = new MixLongThread(this);
            }else if(lightMode == Constant.LIGHT_MODE_HORSE){
                if(horse_bright.getText().toString().equals("") || horse_speed.getText().toString().equals("")){
                    MessageUtil.toastShort(this, "请完善参数");
                    return;
                }
                thread = new MixHorseThread(this);
            }else if(lightMode == Constant.LIGHT_MODE_FLOWING_WATER){
                if(flowingWater_bright.getText().toString().equals("") || flowingWater_speed.getText().toString().equals("")){
                    MessageUtil.toastShort(this, "请完善参数");
                    return;
                }
                thread = new MixFlowingWaterThread(this);
            }else if(lightMode == Constant.LIGHT_MODE_BREATHING){
                if(breathing_time.getText().toString().equals("")){
                    MessageUtil.toastShort(this, "请完善参数");
                    return;
                }
                thread = new MixBreathingThread(this);
            }else if(lightMode == Constant.LIGHT_MODE_COMPOSITE){
                thread = new MixCompositeThread(this);
            }
        }
    }

    /////////////////////////////////////////////////////////////////////////////////////////


    /////////////////////////////////权限区///////////////////////////////////////////

    // 检查权限
    private void checkBlePermission(){
        // 6.0开始就需要动态申请权限
        if (Build.VERSION.SDK_INT >= 23){
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                MessageUtil.toastShort(app, "请打开此APP位置及读取存储器权限");
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN,
                        Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.BLUETOOTH_PERMISSION_CODE);
            }else { // 已有权限，直接连接设备
                bleUtil.connectBLE();
            }
        }
    }

    // 权限回调函数
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case Constant.BLUETOOTH_PERMISSION_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED
                        && grantResults[2] == PackageManager.PERMISSION_GRANTED&& grantResults[3] == PackageManager.PERMISSION_GRANTED) {
                    bleUtil.connectBLE();
                } else {
                    tips.setText(" 点击连接设备 ");
                    tips.setTextColor(Color.RED);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case Constant.BLUETOOTH_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    // 用户同意开启蓝牙，查看权限，然后连接设备
                    checkBlePermission();
                }else {
                    tips.setText(" 点击连接设备 ");
                    tips.setTextColor(Color.RED);
                }
                break;
            default:
                break;
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////



    /////////////////////////////////模式参数区///////////////////////////////////////////

    // 初始化参数区的控件
    private void initOptions(){
        longMode = findViewById(R.id.longMode);
        horse = findViewById(R.id.horse);
        flowingWater = findViewById(R.id.flowingWater);
        breathing = findViewById(R.id.breathing);
        composite = findViewById(R.id.composite);
        // 常亮区参数
        long_bright = findViewById(R.id.long_bright);
        long_interval = findViewById(R.id.long_interval);
        long_offtime = findViewById(R.id.long_offtime);
        long_circle = findViewById(R.id.long_circle);
        long_bright_div = findViewById(R.id.long_bright_div);
        long_interval_div = findViewById(R.id.long_interval_div);
        long_offtime_div = findViewById(R.id.long_offtime_div);
        long_circle_div = findViewById(R.id.long_circle_div);
        // 跑马区
        horse_bright_div = findViewById(R.id.horse_bright_div);
        horse_count_div = findViewById(R.id.horse_count_div);
        horse_direction_div = findViewById(R.id.horse_direction_div);
        horse_circle_div = findViewById(R.id.horse_circle_div);
        horse_speed_div = findViewById(R.id.horse_speed_div);
        horse_bright = findViewById(R.id.horse_bright);
        horse_count = findViewById(R.id.horse_count);
        horse_direction = findViewById(R.id.horse_direction);
        horse_circle = findViewById(R.id.horse_circle);
        horse_speed = findViewById(R.id.horse_speed);
        horse_clockwise = findViewById(R.id.horse_clockwise);
        horse_anticlockwise = findViewById(R.id.horse_anticlockwise);
        // 流水区
        flowingWater_bright_div = findViewById(R.id.flowingWater_bright_div);
        flowingWater_direction_div = findViewById(R.id.flowingWater_direction_div);
        flowingWater_speed_div = findViewById(R.id.flowingWater_speed_div);
        flowingWater_circle_div = findViewById(R.id.flowingWater_circle_div);
        flowingWater_bright = findViewById(R.id.flowingWater_bright);
        flowingWater_direction = findViewById(R.id.flowingWater_direction);
        flowingWater_speed = findViewById(R.id.flowingWater_speed);
        flowingWater_circle = findViewById(R.id.flowingWater_circle);
        flowingWater_clockwise = findViewById(R.id.flowingWater_clockwise);
        flowingWater_anticlockwise = findViewById(R.id.flowingWater_anticlockwise);
        // 呼吸区
        breathing_time_div = findViewById(R.id.breathing_time_div);
        breathing_circle_div = findViewById(R.id.breathing_circle_div);
        breathing_bright_div = findViewById(R.id.breathing_bright_div);
        breathing_time = findViewById(R.id.breathing_time);
        breathing_circle = findViewById(R.id.breathing_circle);
        breathing_bright = findViewById(R.id.breathing_bright);
        // 复合区
        remain = findViewById(R.id.remain);
        setRemain();
    }

    // 绑定参数区的事件
    private void bindOptions(){
        // 常亮区
        long_bright.setOnFocusChangeListener(this);
        long_interval.setOnFocusChangeListener(this);
        long_offtime.setOnFocusChangeListener(this);
        long_circle.setOnFocusChangeListener(this);
        long_bright.setOnEditorActionListener(this);
        long_interval.setOnEditorActionListener(this);
        long_offtime.setOnEditorActionListener(this);
        long_circle.setOnEditorActionListener(this);
        // 跑马区
        horse_bright.setOnFocusChangeListener(this);
        horse_count.setOnFocusChangeListener(this);
        horse_circle.setOnFocusChangeListener(this);
        horse_speed.setOnFocusChangeListener(this);
        horse_bright.setOnEditorActionListener(this);
        horse_count.setOnEditorActionListener(this);
        horse_circle.setOnEditorActionListener(this);
        horse_speed.setOnEditorActionListener(this);
        horse_direction.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                if(checkedId == R.id.horse_clockwise){
                    horse_direction_value = Constant.CLOCKWISE;
                }else if(checkedId == R.id.horse_anticlockwise){
                    horse_direction_value = Constant.ANTICLOCKWISE;
                }
            }
        });
        // 流水区
        flowingWater_bright.setOnFocusChangeListener(this);
        flowingWater_speed.setOnFocusChangeListener(this);
        flowingWater_circle.setOnFocusChangeListener(this);
        flowingWater_bright.setOnEditorActionListener(this);
        flowingWater_speed.setOnEditorActionListener(this);
        flowingWater_circle.setOnEditorActionListener(this);
        flowingWater_direction.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                if(checkedId == R.id.flowingWater_clockwise){
                    flowingWater_direction_value = Constant.CLOCKWISE;
                }else if(checkedId == R.id.flowingWater_anticlockwise){
                    flowingWater_direction_value = Constant.ANTICLOCKWISE;
                }
            }
        });
        // 呼吸区
        breathing_time.setOnFocusChangeListener(this);
        breathing_circle.setOnFocusChangeListener(this);
        breathing_bright.setOnFocusChangeListener(this);
        breathing_time.setOnEditorActionListener(this);
        breathing_circle.setOnEditorActionListener(this);
        breathing_bright.setOnEditorActionListener(this);
    }

    // 处理edittext失去焦点事件
    private void doLostFocus(View view, String defultValue, int minValue, int maxValue){
        // 强制转为 EditText
        EditText editText = (EditText) view;
        // 如果什么值都没填，使用默认值填上
        String text = editText.getText().toString();
        if(text.equals("")){
            editText.setText(defultValue);
            return;
        }
        // 转为int并判断，将值设为1-250之间
        int i = Integer.parseInt(text);
        if(i < minValue){
            editText.setText(minValue + "");
        }else if(i > maxValue){
            editText.setText(maxValue + "");
        }
    }

    // 将参数区所有的模式都不可见
    private void invisibleAllOptions(){
        longMode.setVisibility(View.GONE);
        horse.setVisibility(View.GONE);
        flowingWater.setVisibility(View.GONE);
        breathing.setVisibility(View.GONE);
        composite.setVisibility(View.GONE);
    }

    //////////////////////////////////////////////////////////////////////////////////////


    /////////////////////////////////颜色预设区///////////////////////////////////////////

    // 初始化颜色预设区域的控件
    private void initColors(){
        color0 = findViewById(R.id.color0);
        color1 = findViewById(R.id.color1);
        color2 = findViewById(R.id.color2);
        color3 = findViewById(R.id.color3);
        color4 = findViewById(R.id.color4);
        color5 = findViewById(R.id.color5);
        color6 = findViewById(R.id.color6);
        color7 = findViewById(R.id.color7);
        color8 = findViewById(R.id.color8);
        color9 = findViewById(R.id.color9);
        color10 = findViewById(R.id.color10);
        color11 = findViewById(R.id.color11);
        color12 = findViewById(R.id.color12);
        color13 = findViewById(R.id.color13);
        color14 = findViewById(R.id.color14);
        color15 = findViewById(R.id.color15);
        color16 = findViewById(R.id.color16);
        color17 = findViewById(R.id.color17);
        color18 = findViewById(R.id.color18);
        color19 = findViewById(R.id.color19);
        color0_text = findViewById(R.id.color0_text);
        color1_text = findViewById(R.id.color1_text);
        color2_text = findViewById(R.id.color2_text);
        color3_text = findViewById(R.id.color3_text);
        color4_text = findViewById(R.id.color4_text);
        color5_text = findViewById(R.id.color5_text);
        color6_text = findViewById(R.id.color6_text);
        color7_text = findViewById(R.id.color7_text);
        color8_text = findViewById(R.id.color8_text);
        color9_text = findViewById(R.id.color9_text);
        color10_text = findViewById(R.id.color10_text);
        color11_text = findViewById(R.id.color11_text);
        color12_text = findViewById(R.id.color12_text);
        color13_text = findViewById(R.id.color13_text);
        color14_text = findViewById(R.id.color14_text);
        color15_text = findViewById(R.id.color15_text);
        color16_text = findViewById(R.id.color16_text);
        color17_text = findViewById(R.id.color17_text);
        color18_text = findViewById(R.id.color18_text);
        color19_text = findViewById(R.id.color19_text);
    }

    // 绑定颜色预设区点击事件
    private void bindColors(){
        right.setOnClickListener(this);
        wrong.setOnClickListener(this);
        color0.setOnClickListener(this);
        color1.setOnClickListener(this);
        color2.setOnClickListener(this);
        color3.setOnClickListener(this);
        color4.setOnClickListener(this);
        color5.setOnClickListener(this);
        color6.setOnClickListener(this);
        color7.setOnClickListener(this);
        color8.setOnClickListener(this);
        color9.setOnClickListener(this);
        color10.setOnClickListener(this);
        color11.setOnClickListener(this);
        color12.setOnClickListener(this);
        color13.setOnClickListener(this);
        color14.setOnClickListener(this);
        color15.setOnClickListener(this);
        color16.setOnClickListener(this);
        color17.setOnClickListener(this);
        color18.setOnClickListener(this);
        color19.setOnClickListener(this);
        color0.setOnLongClickListener(this);
        color1.setOnLongClickListener(this);
        color2.setOnLongClickListener(this);
        color3.setOnLongClickListener(this);
        color4.setOnLongClickListener(this);
        color5.setOnLongClickListener(this);
        color6.setOnLongClickListener(this);
        color7.setOnLongClickListener(this);
        color8.setOnLongClickListener(this);
        color9.setOnLongClickListener(this);
        color10.setOnLongClickListener(this);
        color11.setOnLongClickListener(this);
        color12.setOnLongClickListener(this);
        color13.setOnLongClickListener(this);
        color14.setOnLongClickListener(this);
        color15.setOnLongClickListener(this);
        color16.setOnLongClickListener(this);
        color17.setOnLongClickListener(this);
        color18.setOnLongClickListener(this);
        color19.setOnLongClickListener(this);
    }

    // 处理预设区点击事件
    private void doColorClick(int num){
        // 如果灯珠区没有选中的灯珠或者点击的是没有预设颜色的块，则直接选择颜色
        if(num == colors.size() || choosedLights.size() <= 0){
            color_choose.setVisibility(View.VISIBLE);
            currentColorNum = num;
        }else { // 将选中的灯珠设置为预设的颜色
            for (Integer key : choosedLights.keySet()) {
                lights.put(key, num);
                lights_4display.put(key, new int[]{colors.get(num)[0],colors.get(num)[1],colors.get(num)[2]});
            }
            lightDiv.invalidate();
        }
    }

    // 删除某个编号的颜色
    private void removeColor(int num){
        // 如果该编号没有配置颜色，直接返回
        if(colors.get(num) == null){
            return;
        }
        // 如果这是配置过的最后一个颜色，那直接删除
        if(colors.get(num + 1) == null){
            colors.remove(num);
        }else {
            // 将后面的每一个都往前挪一格
            for(int i = num; i < Constant.COLOR_COUNT; i++){
                if(colors.get(i + 1) == null){
                    break;
                }
                colors.put(i, colors.get(i + 1));
                colors.remove(i + 1);
            }
        }
        doColors();
        // 将新的预设颜色存入SharedPreference
        SharedPreferencesUtil.setColors(colors);
    }

    // 处理颜色预设区
    private void doColors(){
        CardView colorZone;
        TextView colorText;
        for(int i = 0; i < Constant.COLOR_COUNT; i++){
            int colorId = getResources().getIdentifier("color"+ i,"id",getPackageName());
            int colorTextId = getResources().getIdentifier("color"+ i + "_text","id",getPackageName());
            colorZone = findViewById(colorId);
            colorText = findViewById(colorTextId);
            int[] color = colors.get(i);
            if(color != null){ // 这个颜色已经有预设，显示颜色
                colorZone.setVisibility(View.VISIBLE);
                colorZone.setCardBackgroundColor(Color.rgb(color[0],color[1],color[2]));
                colorText.setVisibility(View.INVISIBLE);
            }else { // 没有过颜色预设
                if(i == colors.size()){ // 当前循环到的就是该显示添加标志的控件
                    colorZone.setVisibility(View.VISIBLE);
                    colorZone.setCardBackgroundColor(Color.rgb(238,238,238));
                    colorText.setVisibility(View.VISIBLE);
                }else { // 剩下的直接全部不显示
                    colorZone.setVisibility(View.INVISIBLE);
                }
            }
        }

    }

    //////////////////////////////////////////////////////////////////////////////////////
    /**
     * 设置为竖屏
     */
    @Override
    protected void onResume() {
        if(getRequestedOrientation()!= ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        super.onResume();
    }

    /**
     * 主线程刷新灯珠区域
     */
    public void refreshLightsDiv(){
        lightDiv.invalidate();
    }

    //重新查询所有的模版信息，并重新生成adapter，刷新recyclerView
    public void updateRecycleView(){
        List<CompositeItem> CompositeList = LitePal.where("colorMode=?",colorMode + "").order("id asc").find(CompositeItem.class);
        adapter = new CompositeItemAdapter(CompositeList,this);
        recycler_view.setLayoutManager(new LinearLayoutManager(this));
        recycler_view.setAdapter(adapter);
    }

    //查询当前模式下的已用字节数，并算出剩余的字节数显示在控件上
    public void setRemain(){
        int result = LitePal.where("colorMode=?",colorMode + "").sum(CompositeItem.class, "byteCount", int.class);
        remain.setText((Constant.TOTAL_BYTE_COUNT - result) + "");
    }

    // 打开修改的fragment页面
    public void openCompositeEditFragment(CompositeItem item){
        if(!isCompositeAddOpened){
            CompositeEditFragment fragment = new CompositeEditFragment(this,item);
            fragment.setCancelable(false);
            fragment.show(getSupportFragmentManager(),"");
            isCompositeAddOpened = true;
        }
    }
}



